package component.controls
{
	import component.controls.ui.Component;
	import component.global.ComponentSetting;
	import component.global.consts.Directions;
	import component.global.utils.ObjectUtil;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	
	public class Box extends Component
	{
		public static const ON_RESIZE:String = "onResize";
		public function Box(direction:String = Directions.VERTICAL,spacing:int = ComponentSetting.BOX_DEFAULT_SPACING)
		{
			_direction = direction;
			_spacing = spacing;
			super();
		}
		
		protected var _direction:String;
		protected var _spacing:int;
		protected var _displayObjects:Array;
		
		override protected function init():void{
			_displayObjects = [];
		}
		
		public function addContent(child:DisplayObject):DisplayObject{
			if(child == null)return child;
			if(_displayObjects.length>0){
				var foreItem:DisplayObject = _displayObjects[_displayObjects.length - 1];
				if(_direction == Directions.HORIZONTAL){
					child.x = foreItem.x + foreItem.width + _spacing;
				} else if (_direction == Directions.VERTICAL) {
					child.y = foreItem.y + foreItem.height + _spacing;
				}
			} else {
				child.x = child.y = 0;
			}
			_displayObjects.push(child);
			addChild(child);
			
			dispatchEvent(new Event(Box.ON_RESIZE));
			return child;
		}
		
		public function removeContent(child:DisplayObject):DisplayObject{
			if(child == null)return child;
			var idx:int = _displayObjects.indexOf(child);
			if(idx<0)return child;
			_displayObjects.splice(idx,1);
			for (var i:int = idx; i < _displayObjects.length; i++) 
			{
				if(_direction == Directions.HORIZONTAL){
					_displayObjects[i].x -= (child.width + _spacing);
				} else if (_direction == Directions.VERTICAL){
					_displayObjects[i].y -= (child.height + _spacing);
				}
			}
			removeChild(child);
			dispatchEvent(new Event(Box.ON_RESIZE));
			return child;
		}
		
		override public function dispose():void{
			super.dispose();
			ObjectUtil.disposeElements(_displayObjects);
		}
	}
}